package com.github.postsanf.yinian.timeline;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.RotateAnimation;
import android.widget.AdapterView;
import android.widget.TextView;

import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.YNTimeLineActivity;
import com.github.postsanf.yinian.bean.YNCompassPic;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.entity.YNCompassPicResponse;
import com.github.postsanf.yinian.gallery.GalleryFlow;
import com.github.postsanf.yinian.gallery.ImageAdapter;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.TimeUtils;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

public class ThirdFragment extends BaseTimelineFragment {

    private List<YNCompassPic> picDatas = new ArrayList<>();
    private float  lastDegree = 2;
    private String curYear;
    private String curMonth;
    private String curGroup;
    private View mView;
    private  RotateAnimation animation;
    private GalleryFlow customGallery;
    private TextView    title;
    private ImageAdapter adapter;
    private int[] mAnimationViewIds = {
            R.id.timeline_third_center,R.id.timeline_second_gball,
            R.id.timeline_third_ship,R.id.rl_third_left_return,R.id.rl_third_right_return,R.id.timeline_third_pointer,R.id.timeline_third_top_ball
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        mView = LayoutInflater.from(getActivity()).inflate(R.layout.timeline_third, container, false);
        initView();
        return  mView;
    }

    public void doChange(){
            curYear  = ((YNTimeLineActivity)getActivity()).getCurYear() == null ? "0" :((YNTimeLineActivity)getActivity()).getCurYear();
            curMonth = ((YNTimeLineActivity)getActivity()).getCurMonth() == null ? "0" :((YNTimeLineActivity)getActivity()).getCurMonth();
            curGroup = ((YNTimeLineActivity)getActivity()).getCurGroup() == null ? "0" :((YNTimeLineActivity)getActivity()).getCurGroup();
            title.setText(curMonth+"月");
            initData();
    }

    private void initView(){
        title = (TextView) mView.findViewById(R.id.tv_cur_month);
        customGallery = (GalleryFlow) mView.findViewById(R.id.third_gallery);
        adapter = new ImageAdapter(getActivity(), picDatas,imageLoader);
        customGallery.setAdapter(adapter);
        customGallery.setSelection(0);

        ViewGroup.LayoutParams gf = customGallery.getLayoutParams();
        gf.height =  DisplayUtils.getScreenHeightPixels(getActivity())*2/3;
        customGallery.setLayoutParams(gf);

        customGallery.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                // 获取选中照片的发布时间
                String  time = picDatas.get(position).getPmemorytime();
                if (time==null ||  time.trim().length()==0){
                    //设置为正中
                    setTimePointer(15);
                }else{
                    setTimePointer(TimeUtils.getDayByTime(time));
                }
                adapter.notifyDataSetChanged();

            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        mView.findViewById(mAnimationViewIds[3]).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v){
                ((YNTimeLineActivity)getActivity()).switchPage(1);
            }
        });
        mView.findViewById(mAnimationViewIds[4]).setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
    }

    private void initData(){
        LinkedHashMap<String,String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_P_ID,"-1");
        mParam.put(CommonConstants.YNS_GROUP_ID,curGroup);
        mParam.put(CommonConstants.YNS_YEAR,curYear);
        mParam.put(CommonConstants.YNS_MONTH,curMonth);

        StringRequest req = new StringRequest(getString(R.string.BASE_URL)+getString(R.string.ynShowPhotosInTimeCompass))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true){
                    @Override
                    public void onSuccess(String s, Response<String> response){
                        YNCompassPicResponse resCompassPic = gson.fromJson(s, YNCompassPicResponse.class);
                        if (resCompassPic!=null && ReqUtils.isSuccess(resCompassPic.getCode())){
                            picDatas.clear();
                            if(resCompassPic.getData().size() == 0){
                                picDatas.add(new YNCompassPic("",CommonConstants.defualt_iv3_url,"1"));
                            }else{
                                picDatas.addAll(resCompassPic.getData());
                            }
                            adapter.notifyDataSetChanged();
                        }else{
                            showToast("请求失败");
                        }
                    }
                    @Override
                    public void onFailure(HttpException e, Response<String> response){
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }


    private Animation getBallAnimation(int resID){
        Animation animation = AnimationUtils.loadAnimation(getActivity(),resID);
        return animation;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mView.findViewById(mAnimationViewIds[0]).startAnimation(getBallAnimation(R.anim.anim_second_center));
        mView.findViewById(mAnimationViewIds[1]).startAnimation(getBallAnimation(R.anim.anim_second_gball));
        mView.findViewById(mAnimationViewIds[6]).startAnimation(getBallAnimation(R.anim.anim_third_topball));
    }


    public void setTimePointer(int time){
        if(lastDegree == time){return;}
        float degree = 6 +(time-1) * 5.5f - 90;
        animation =new RotateAnimation(lastDegree,degree,Animation.RELATIVE_TO_SELF, 0.5f,Animation.RELATIVE_TO_SELF,0.95f);
        animation.setDuration((long) (1000*Math.abs((lastDegree-degree)/90)));
        animation.setFillAfter(true);
        mView.findViewById(mAnimationViewIds[5]).startAnimation(animation);
        lastDegree = degree;
    }

    @Override
    public int[] getChildViewIds() {
        return new int[]{
                R.id.iv_timeline_ball1,R.id.iv_timeline_ball2,
                R.id.iv_timeline_ball3,R.id.iv_timeline_ball4,R.id.rl_timeline_start
        };
    }

    @Override
    public int getRootViewId() {
        return R.id.root_timeline_first;
    }
}
